package com.lx.pc.restful.wx;

import java.io.IOException;
import java.math.BigInteger;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.lx.pc.domain.vo.account.AccountVo;
import com.lx.pc.domain.vo.accountlog.AccountLogVo;
import com.lx.pc.domain.vo.evaluate.EvaluateVo;
import com.lx.pc.domain.vo.paypass.PayPassVo;
import com.lx.pc.domain.vo.transaction.TransactionVo;
import com.lx.pc.domain.vo.transactionlog.TransactionLogVo;
import com.lx.pc.domain.vo.user.UserVo;
import com.lx.pc.domain.vo.wcategory.WCategoryVo;
import com.lx.pc.domain.vo.worder.WOrderVo;
import com.lx.pc.domain.vo.worderprice.WOrderPriceVo;
import com.lx.pc.domain.vo.wx.WeixinVo;
import com.lx.pc.restful.util.AjaxResult;
import com.lx.pc.service.account.IAccountService;
import com.lx.pc.service.accountlog.IAccountLogService;
import com.lx.pc.service.evaluate.IEvaluateService;
import com.lx.pc.service.paypass.IPayPassService;
import com.lx.pc.service.transaction.ITransactionService;
import com.lx.pc.service.transactionog.ITransactionLogService;
import com.lx.pc.service.user.IUserService;
import com.lx.pc.service.wcategory.IWCategoryService;
import com.lx.pc.service.worder.IWOrderService;
import com.lx.pc.service.worderCategory.IWOrderCategoryService;
import com.lx.pc.service.worderprice.IWOrderPriceService;
import com.lx.pc.service.wx.IWeixinService;
import com.lx.pc.utils.Constants;
import com.lx.pc.utils.DateUtil;
import com.lx.pc.utils.OmsPage;
import com.lx.pc.utils.RandomUtils;
import com.lx.pc.utils.Utils;

@Controller
@RequestMapping("/wx")
public class OrderController {
	
	/**
	 * 用户
	 */
	@Resource(name = "userService")
	private IUserService userService;
	
	/**
	 * 微信获取token
	 */
	@Resource(name = "weixinService")
	private IWeixinService weixinService;
	
	/**
	 * 用户订单
	 */
	@Resource(name = "wOrderService")
	private IWOrderService wOrderService;
	
	/**
	 * 用户多个分类多个重量
	 */
	@Resource(name = "wOrderCategoryService")
	private IWOrderCategoryService wOrderCategoryService;
	
	/**
	 * 定价
	 */
	@Resource(name = "wOrderPriceService")
	private IWOrderPriceService wOrderPriceService;
	
	/**
	 * 分类
	 */
	@Resource(name = "wCategoryService")
	private IWCategoryService wCategoryService;
	
	/**
	 * 个人账户
	 */
	@Resource(name = "accountService")
	private IAccountService accountService;
	
	/**
	 * 个人账户明细
	 */
	@Resource(name = "accountLogService")
	private IAccountLogService accountLogService;
	
	/**
	 * 交易记录
	 */
	@Resource(name = "transactionService")
	private ITransactionService transactionService;
	
	/**
	 * 交易明细
	 */
	@Resource(name = "transactionLogService")
	private ITransactionLogService transactionLogService;
	
	/**
	 * 支付密码设置
	 */
	@Resource(name = "payPassService")
	private IPayPassService payPassService;
	
	/**
	 * 订单评价
	 */
	@Resource(name = "evaluateService")
	private IEvaluateService evaluateService;

	/**
	 * 获取当前商家的订单
	 * @param v
	 * @param page
	 * @param size
	 * @return
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping("/serchReceiptOrderList")
    public  String serchReceiptOrderList(WOrderVo v,Integer page,Integer size) throws IOException {
        Map<String,Object> result = new HashMap<String, Object>();
        OmsPage<WOrderVo> pages = wOrderService.findByWOrder(v, page, size);
        result.put("wOrderVo", pages.getResult());
        result.put("pages", pages);
        return JSON.toJSONString(result);
	}
	
	/**
	 * 修改订单状态--取消订单
	 */
	@ResponseBody
	@RequestMapping("/updateOrderStatus")
    public  AjaxResult<String> updateOrderStatus(WOrderVo v) throws IOException {
		AjaxResult<String> ajaxResult = new AjaxResult<String>();
		WOrderVo orderVo = wOrderService.find(new BigInteger(v.getbId()));
		orderVo.setStatus(v.getStatus());
		String flag = wOrderService.updateStatus(orderVo);
		ajaxResult.setMsg(flag);
		return ajaxResult;
	}
	
	/**
	 * 过磅定价
	 */
	@RequestMapping("/toPriced")
	public ModelAndView toPriced(WOrderVo v) {
		ModelAndView mv = new ModelAndView("/wx/seller/priced");
		WOrderVo orderVo = wOrderService.findByOrderNum(v);
		WCategoryVo categoryVo = new WCategoryVo();
		List<WCategoryVo> listCategory = wCategoryService.findByWCategory(categoryVo);
		
		mv.addObject("listCategory",listCategory);
		mv.addObject("orderVo",orderVo);
		return mv;
	}
	
	/**
	 * 小程序过磅定价 分类信息
	 */
	@ResponseBody
	@RequestMapping("/toHomePriced.do")
    public  String toHomePriced(WOrderVo v){
		Map<String,Object> result = new HashMap<String, Object>();
		WOrderVo orderVo = wOrderService.findByOrderNum(v);
		WCategoryVo categoryVo = new WCategoryVo();
		List<WCategoryVo> listCategory = wCategoryService.findByWCategory(categoryVo);
        
		result.put("listCategory", listCategory);
		result.put("orderVo", orderVo);
		
		return JSON.toJSONString(result);
	}
	
	/**
	 * 小程序过磅定价
	 * @param v
	 * @param categoryStr
	 * @param actualWeightStr
	 * @param priceStr
	 * @return
	 * @throws ParseException
	 */
	@ResponseBody
	@RequestMapping(value = "/toUpdateOrder.do")
	public AjaxResult<String> toUpdateOrder(WOrderVo v,
			@RequestParam(value = "categoryStr[]")String[] categoryStr,
			@RequestParam(value = "actualWeightStr[]")String[] actualWeightStr,
			@RequestParam(value = "priceStr[]")String[] priceStr) throws ParseException{
		
		AjaxResult<String> ajaxResult = new AjaxResult<String>();
		
		WOrderVo orderVo = wOrderService.find(v.getId());
		orderVo.setStatus(v.getStatus());
		//支付状态 1 支付成功 2 未支付
		orderVo.setPaymentStatus(2);
		wOrderService.updateStatus(orderVo);
		
		if (categoryStr != null) {
			//分类
			for (int i = 0 ;i<categoryStr.length; i++) {
				WOrderPriceVo orderPriceVo = new WOrderPriceVo();
				//分类id
				orderPriceVo.setwCategoryId(categoryStr[i]);
				//订单编号
				orderPriceVo.setOrderNumber(orderVo.getOrderNumber());
				//确认重量
				orderPriceVo.setActualWeight(actualWeightStr[i]);
				//价格
				orderPriceVo.setPrice(Float.valueOf(priceStr[i]));
				
				wOrderPriceService.save(orderPriceVo);
			}
		}
		
		ajaxResult.setMsg("1");
		ajaxResult.setResult(orderVo.getOrderNumber());
		return ajaxResult;
	}
	
	/**
	 * 修改订单状态
	 * @param v
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/toUpdateStatus.do")
	public AjaxResult<String> toUpdateStatus(WOrderVo v){
		AjaxResult<String> ajaxResult = new AjaxResult<String>();
		
		WOrderVo orderVo = wOrderService.find(v.getId());
		PayPassVo passVo = payPassService.findByPayUserId(orderVo.getReceiptId());
		String password = Utils.md5(v.getPassword(), Constants.PAY_PASS_CACHE_KEY);
		if (v.getPaymentType() != 1) {
			if (!passVo.getPassword().equals(password)) {
				ajaxResult.setMsg("2");
				return ajaxResult;
			}
		}
		//状态 1 进行中 2 已完成 3 已取消 4 无人接单
		orderVo.setStatus(2);
		//支付方式 1 线下 2 微信 3 银行卡 4 余额
		orderVo.setPaymentType(v.getPaymentType());
		//支付状态 1 支付成功 2 未支付
		orderVo.setPaymentStatus(1);
		
		wOrderService.updateStatus(orderVo);
		
		//获取微信token
		WeixinVo weixinVo = weixinService.findByWeixin();
		//查询回收员名称和电话
		UserVo vo = userService.find(new BigInteger(orderVo.getUserId()));
		//发送消息模版
		Map<String,TemplateData> param = new HashMap<>();
		
		//发送消息模版使用的分类属性
		String category = "";
		WOrderPriceVo orderPriceVo = new WOrderPriceVo();
		orderPriceVo.setOrderNumber(orderVo.getOrderNumber());
		
		//品类
		List<WOrderPriceVo> orderPriceVos = wOrderPriceService.findByWOrderPrice(orderPriceVo);
		if (orderPriceVos.size()>0) {
			for (WOrderPriceVo orderPrice : orderPriceVos) {
				category += orderPrice.getPriceName() +" "+ orderPrice.getActualWeight() +"kg" +" "+ orderPrice.getPrice() +"元/kg";
			}
		}
		//已完成 公众号订单消息推送
		if (orderVo.getPickTime() != null) {
			param.put("first",new TemplateData("预约时间："+orderVo.getPickTime() + "已结算","#173177"));
		}else {
			param.put("first",new TemplateData("扫码订单："+ "已结算","#173177"));
		}
        param.put("orderMoneySum",new TemplateData(String.valueOf(v.getCountPrice())+"元","#173177"));
        param.put("orderProductName",new TemplateData(category,"#173177"));
        String time = DateUtil.getDateTimeFormat(orderVo.getModifyTime());
		param.put("Remark",new TemplateData("支付时间："+time+" \r\n","#173177"));
        //调用发送微信消息给用户的接口
        WeiXinUtils.sendWechatMsgToUser(weixinVo.getAccessToken(),vo.getWxOpenId(),Constants.TEMPLATE_ORDER, "", "#173177", WeiXinUtils.packJsonmsg(param));
		
        if (v.getPaymentType() != 1) {
        	/*** ------------------账户收入方开始 ------------------- */
			//收入用户
			AccountVo accountVo = accountService.findByUserId(orderVo.getUserId());
			
			//总价
			accountVo.setAmount(accountVo.getAmount() + v.getCountPrice());
			//修改收入总价
			accountService.update(new BigInteger(accountVo.getbId()), 1L, accountVo);
			
			//日志
			AccountLogVo accountLogVo = new AccountLogVo();
			//账户余额
			accountLogVo.setAmount(accountVo.getAmount());
			//账户id
			accountLogVo.setAccountId(accountVo.getbId());
			//订单编号
			accountLogVo.setBusinessNumber(orderVo.getOrderNumber());
			//回收员类型 1 充值 2 提现 3 支出 4 收入
			accountLogVo.setBusinessType("4");
			//总价格
			accountLogVo.setPrice(v.getCountPrice());
			//接收人
			accountLogVo.setUserId(orderVo.getUserId());
			//添加明细
			accountLogService.save(accountLogVo);
			/*** ------------------账户收入方 结束------------------- */
			
			
			/*** ------------------账户支付方 开始------------------- */
			//支出用户
			AccountVo account = accountService.findByUserId(orderVo.getReceiptId());
			//总价
			account.setAmount(account.getAmount() - v.getCountPrice());
			//修改支出总价
			accountService.update(new BigInteger(account.getbId()), 1L, account);
			
			//日志记录
			AccountLogVo accountLogVo2 = new AccountLogVo();
			//支付金额
			accountLogVo2.setAmount(account.getAmount());
			//账户id
			accountLogVo2.setAccountId(accountVo.getbId());
			//订单编号
			accountLogVo2.setBusinessNumber(orderVo.getOrderNumber());
			//回收员类型 1 充值 2 提现 3 支出 4 收入
			accountLogVo2.setBusinessType("3");
			//总价格
			accountLogVo2.setPrice(v.getCountPrice());
			//发起人
			accountLogVo2.setUserId(orderVo.getReceiptId());
			//添加明细
			accountLogService.save(accountLogVo2);
			/*** ------------------账户支付方 结束 ------------------- */
			
			/*** ------------------订单交易明细开始------------------- */
			//订单交易明细
			TransactionVo transactionVo = new TransactionVo();
			//订单编号
			transactionVo.setOrderId(orderVo.getOrderNumber());
			//交易编号
			transactionVo.setTranNumber(RandomUtils.random6());
			//交易明细添加
			transactionService.save(transactionVo);
			/*** ------------------订单交易明细结束------------------- */
			
			/*** ------------------订单交易日志收入方开始------------------- */		
			//交易明细日志
			TransactionLogVo logVo = new TransactionLogVo();
			//交易编号
			logVo.setTrId(transactionVo.getTranNumber());
			//发起人
			logVo.setUserId(orderVo.getUserId());
			//回收员类型 1 支出 2 收入
			logVo.setTranType(2);
			//支付通道 1 微信 2 支付宝 3 线下 4 余额 
			logVo.setChannelPayflag(v.getPaymentType());
			//总价
			logVo.setPrice(v.getCountPrice());
			//交易明细日志添加
			transactionLogService.save(logVo);
			/*** ------------------订单交易收入方结束------------------- */		
			
			/*** ------------------订单交易支付方开始------------------- */		
			//交易明细日志
			TransactionLogVo logVo2 = new TransactionLogVo();
			//交易编号
			logVo2.setTrId(transactionVo.getTranNumber());
			//接受人
			logVo2.setUserId(orderVo.getReceiptId());
			//回收员类型 1 支出 2 收入
			logVo2.setTranType(1);
			//支付通道 1 微信 2 支付宝 3 线下 4 余额 
			logVo2.setChannelPayflag(v.getPaymentType());
			//总价
			logVo2.setPrice(v.getCountPrice());
			//交易明细日志添加
			transactionLogService.save(logVo2);
			/*** ------------------订单交易支付方结束------------------- */		
        }else {
        	/*** ------------------订单交易明细开始------------------- */
			//订单交易明细
			TransactionVo transactionVo = new TransactionVo();
			//订单编号
			transactionVo.setOrderId(orderVo.getOrderNumber());
			//交易编号
			transactionVo.setTranNumber(RandomUtils.random6());
			//交易明细添加
			transactionService.save(transactionVo);
			/*** ------------------订单交易明细结束------------------- */
			
			/*** ------------------订单交易日志收入方开始------------------- */		
			//交易明细日志
			TransactionLogVo logVo = new TransactionLogVo();
			//交易编号
			logVo.setTrId(transactionVo.getTranNumber());
			//发起人
			logVo.setUserId(orderVo.getUserId());
			//回收员类型 1 支出 2 收入
			logVo.setTranType(2);
			//支付通道 1 微信 2 支付宝 3 线下 4 余额 
			logVo.setChannelPayflag(v.getPaymentType());
			//总价
			logVo.setPrice(v.getCountPrice());
			//交易明细日志添加
			transactionLogService.save(logVo);
			/*** ------------------订单交易收入方结束------------------- */		
			
			/*** ------------------订单交易支付方开始------------------- */		
			//交易明细日志
			TransactionLogVo logVo2 = new TransactionLogVo();
			//交易编号
			logVo2.setTrId(transactionVo.getTranNumber());
			//接受人
			logVo2.setUserId(orderVo.getReceiptId());
			//回收员类型 1 支出 2 收入
			logVo2.setTranType(1);
			//支付通道 1 微信 2 支付宝 3 线下 4 余额 
			logVo2.setChannelPayflag(v.getPaymentType());
			//总价
			logVo2.setPrice(v.getCountPrice());
			//交易明细日志添加
			transactionLogService.save(logVo2);
			/*** ------------------订单交易支付方结束------------------- */		
        }
		ajaxResult.setMsg("1");
		return ajaxResult;
	}
	
	/**
	 * 我要销货申请
	 * @param v
	 * @return
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping("/toSellthe.do")
	public String toSellthe(WOrderVo v){
		Map<String,Object> result = new HashMap<String, Object>();
		UserVo user = userService.find(new BigInteger(v.getUserId()));
		if (user != null) {
			user.setWxType(4);
			List<UserVo> userVos = userService.findByUserLatLng(user);
			if (userVos.size()>0 ) {
				//接单人
				v.setReceiptId(userVos.get(0).getId().toString());
			}
		}
		
		//设置订单编号
		v.setOrderNumber(RandomUtils.random6());
		//判断当前区域是否有商家
		if (v.getReceiptId() != null) {
			//进行中
			v.setStatus(1);
		}else {
			//无人接单
			v.setStatus(4);
		}
		v.setType(2);
		v.setProvince(user.getProvince());
		v.setCity(user.getCity());
		v.setArea(user.getArea());
		v.setAddress(user.getAddress());
		wOrderService.save(v);
		result.put("msg", "1");
		return JSON.toJSONString(result);
	}
	
	/**
	 * 扫码生成订单
	 * @param v
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/toScanOrder.do")
	public String toScanOrder(WOrderVo v) {
		Map<String,Object> result = new HashMap<String, Object>();
		if (!"".equals(v.getUserId()) && !"".equals(v.getReceiptId())) {
			if (!v.getUserId().equals(v.getReceiptId())) {
				UserVo user = userService.find(new BigInteger(v.getUserId()));
				//接单人
				v.setReceiptId(v.getReceiptId());
				//设置订单编号
				v.setOrderNumber(RandomUtils.random6());
				//判断当前区域是否有商家
				//进行中
				v.setStatus(1);
				//扫码订单
				v.setType(3);
				v.setProvince(user.getProvince());
				v.setCity(user.getCity());
				v.setArea(user.getArea());
				v.setAddress(user.getAddress());
				wOrderService.save(v);
				v.setbId(v.getId().toString());
				result.put("orderVo", v);
				result.put("msg", "1");
			}else {
				result.put("msg", "2");
			}
		}else {
			result.put("msg", "2");
		}
		return JSON.toJSONString(result);
	}
	
	/**
	 * 账户明细
	 * @param v
	 * @param page
	 * @param size
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/toAccountList.do")
	public String toAccountList(AccountVo v,Integer page,Integer size) {
		Map<String,Object> result = new HashMap<String, Object>();
		OmsPage<AccountVo> pages = accountService.findByAccount(v, page, size);
		result.put("accountVo", pages.getResult());
        result.put("pages", pages);
		return JSON.toJSONString(result);
	}
	
	/**
	 * 对账单--交易明细
	 * @param v
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/toTranList.do")
	public String toTranList(TransactionVo v,Integer page,Integer size) {
		Map<String,Object> result = new HashMap<String, Object>();
		OmsPage<TransactionVo> pages = transactionService.findByTransaction(v, page, size);
 		result.put("transactionVo", pages.getResult());
        result.put("pages", pages);
		return JSON.toJSONString(result);
	}
	
	/**
	 * 对账单--收入/支出
	 * @param v
	 * @param page
	 * @param size
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/toTranSumCount.do")
	public String toTranSumCount(TransactionVo v,Integer page,Integer size) {
		Map<String,Object> result = new HashMap<String, Object>();
		//收入
		Float income = 0f;
		//支出
		Float expenditure = 0f;
		if (v.getTranType() != null) {
			if (v.getTranType() == 1) {
				//支出
				expenditure = transactionService.findByTransactionExpenditureCount(v);
			}else if (v.getTranType() == 2) {
				//收入
				income = transactionService.findByTransactionExpenditureCount(v);
			}
		} else {
			//收入
			v.setTranType(2);
			income = transactionService.findByTransactionExpenditureCount(v);
			//支出
			v.setTranType(1);
			expenditure = transactionService.findByTransactionExpenditureCount(v);
		}
		
		v.setIncome(income);
		v.setExpenditure(expenditure);
		
		result.put("transactionVo", v);
		return JSON.toJSONString(result);
	}
	
	/**
	 * 添加评价
	 * @param v
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/toSaveEvaluate.do")
	public String toSaveEvaluate(EvaluateVo v) {
		Map<String,Object> result = new HashMap<String, Object>();
		evaluateService.save(v);
		result.put("msg", "1");
		return JSON.toJSONString(result);
	}
	
	/**
	 * 查询评价列表
	 * @param v
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/serchEvaluateList.do")
	public String serchEvaluateList(EvaluateVo v) {
		Map<String,Object> result = new HashMap<String, Object>();
		List<EvaluateVo> list = evaluateService.findByEvaluate(v);
		result.put("evaluateVo", list);
		return JSON.toJSONString(result);
	}
	
	
	
}
